<?php

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class InsuranceFund extends Model
{
	use SoftDeletes;
	protected $fillable = ['employee_id', 'insurance_temp_id', 'base', 'once', 'remarks', 'expired_at'];
	protected $casts = [
		'expired_at'  => 'datetime:Y-m-d H:i:s'
	];

	public function employee()
	{
		return $this->belongsTo(Employee::class);
	}

	public function insuranceTemp()
	{
		return $this->belongsTo(InsuranceTemp::class);
	}

	public function attachments()
	{
		return $this->morphMany(ObjectStorage::class, 'common')->orderByDesc('created_at');
	}

	public function scopeWhichKeyword($q, $k)
	{
		if (!$k) return $q;
		return $q->where(self::qualifyColumn('remarks'), 'like', "%{$k}%");
	}

	public function scopeWhichEmployee($q, $s, $u = 0)
	{
		if (!$s) return $q;
		if (!is_array($s)) {
			$s = [$s];
		}
		$q->whereIn(self::qualifyColumn('employee_id'), $s);
		if ($u) {
			foreach ($s as $i) {
				DB::table('search_weights')->updateOrInsert(['user_id' => $u, 'employee_id' => $i]);
			}
			DB::table('search_weights')->where('user_id', $u)->whereIn('employee_id', $s)->increment('total');
		}
	}

	public function scopeWhichInsurance($q, $s)
	{
		return $q->when($s, function ($q, $s) {
			if (!is_array($s)) {
				$s = [$s];
			}
			$q->whereIn(self::qualifyColumn('insurance_temp_id'), $s);
		});
	}

	public function scopeWhichAt($c, $a, $d)
	{
		$at = "{$a}_at";
		if (! in_array($at, ["expired_at", "updated_at", "created_at"])) return $c;
        $field = self::qualifyColumn($at);
		if (! is_array($d)) return $c->orderByDesc($field);
		if ($d[0]) $c->where($field, '>=', $d[0]);
		if ($d[1]) $c->where($field, '<=', $d[1]);
	}
}
